
<style lang='scss'>
.label-modal {
  .ivu-modal {
    top: 20px;
  }
}
</style>

<template>
    <div>
		<Alert  v-if="!isquery" class="padding-15" show-icon>操作提示：带有”<span class="color-danger">*</span>“的选项为必填项，其他为选填项。</Alert>
        <div class="margin-bottom-10" v-if="otherData.cancel==0">
            <!-- <Button type="warning"   @click="cancelWaybill" v-if="otherData.status!=0&&otherData.cancel==0&&otherData.isInternational!=1">取消运单</Button> -->
            <Button type="error" class="margin-right-5"  @click="removeWaybill" v-if="otherData.status==0">删除运单</Button>
            <Button type="primary" class="margin-right-5" @click="submit" v-if="!isquery">保存信息</Button>
            <Button type="success" class="margin-right-5" @click="handleCalculate" v-if="otherData.status<1&&otherData.isInternational!=1">获取运单</Button>
            <Button type="info" class="margin-right-5" @click="printWaybill" v-if="otherData.status!=0&&otherData.cancel==0">打印运单</Button>
            <Button type="success" class="margin-right-5" @click="printWayInvoce" v-if="receiverData.receiverCountrycode!=shipperData.shipperCountrycode">打印发票</Button>
            <Button type="warning" class="margin-right-5" v-if="otherData.systemSource == 1" @click="queryApi" >API参数</Button>
			<Button type="success" class="margin-right-5" v-if="otherData.systemSource == 1" @click="queryRate" >测算参数</Button>
            <Button type="warning" class="margin-right-5" v-if="otherData.returnLabel == 1 && !pickUpData.pickupNumber" @click="appointPickUp" >预约取件</Button>
            <Button class="margin-right-5" v-if="pickUpData.pickupNumber" @click="canceltPickUp" >取消预约取件</Button>
        </div>

        <!-- 重新排版 -->
        <div>
            <Row>
                <Col span="16" style="padding-right:7px">
                    <!-- 运单信息 -->
                    <div class="newbase-box">
                        <div class="newbase-title">运单信息</div>
                        <div>
                            <Form class="clearfix padding-right-15 margin-top-5" :label-width="160"  ref='otherData' :model='otherData'>
                                <Row>
                                    <Col span="12">
                                    <FormItem prop='carrier' label="运营商:" :rules='carrierRule'>
                                        <span v-if="isquery">{{otherData.carrier}}</span>
                                        <Select v-else v-model="otherData.carrier" >
                                            <Option value="">无</Option>
                                            <Option value="FedEx">FedEx</Option>
                                            <Option value="UPS">UPS</Option>
                                        </Select>
                                    </FormItem>
                                    </Col>
                                    <Col span="12">
                                    <FormItem label="运营商服务:" >
                                        <span v-if="isquery">{{this.getServiceCode(otherData.serviceCode)}}</span>
                                        <Select v-else v-model="otherData.serviceCode" >
                                            <Option value="">无</Option>
                                            <Option value="FEDXG">Ground</Option>
                                            <Option value="FEDSP">Smart Post</Option>
                                            <Option value="FEDHD">Home Delivery</Option>
                                            <Option value="UPSG">UPSG</Option>
                                        </Select>
                                    </FormItem>
                                    </Col>
                                    <Col span="12">
                                    <FormItem label="运单号码/关联单号:" >
                                        <span>{{otherData.trackingCode}}/{{otherData.parcelNo}}</span>
                                    </FormItem>
                                    </Col>
                                    <Col span="12">
                                    <FormItem label="客户组织:" >
                                        <span>{{getOrgName(otherData.organizationId) || '--'}}</span>
                                    </FormItem>
                                    </Col>
                                    <Col span="12" v-if="isquery">
                                    <FormItem label="是否取消:" >
                                        <div >{{otherData.cancel == 0 ? '否' : '是'}}</div>
                                    </FormItem>
                                    </Col>

                                    <Col span="12">
                                    <FormItem label="预估费用:" >
                                        <span>{{otherData.rate}}&nbsp;{{otherData.currency}}</span>
                                    </FormItem>
                                    </Col>
                                    <Col span="12">
                                    <FormItem label="包裹尺寸:" >
                                        <span>{{parcelData.parcelLength}} * {{parcelData.parcelWidth}} * {{parcelData.parcelHeight}} {{parcelData.parcelLengthUnit}}</span>
                                    </FormItem>
                                    </Col>
                                    <Col span="12">
                                    <FormItem label="包裹重量:" >
                                        <span>{{parcelData.parcelWeight}} {{parcelData.parcelWeightUnit}}</span>
                                    </FormItem>
                                    </Col>
                                    <Col span="12">
                                    <FormItem label="物流状态:" >
                                        <span>{{getStatus(incrementData.trackingStatus)}}</span>
                                    </FormItem>
                                    </Col>
                                    <Col span="12">
                                    <FormItem label="包裹数量:" >
                                        <span>1</span>
                                    </FormItem>
                                    </Col>
                                    <Col span="12">
                                    <FormItem label="保价服务:" >
                                        <span>{{incrementData.valuation == 0 ? '否' : '是'}}</span>
                                    </FormItem>
                                    </Col>
                                    <Col span="12">
                                    <FormItem label="签名服务:">
                                        <span >{{incrementData.signfor ? incrementData.signfor == 0 ? '否' : '是' : '否'}}</span>
                                    </FormItem>
                                    </Col>
                                </Row>
                            </Form>
                        </div>
                    </div>
                    <Row class="margin-top-15">
                        <!-- 发货 收货信息 -->
                        <Col span="12">
                            <div class="newbase-box" style="margin-right:7px;" :style="newheight">
                            <div class="newbase-title">发件信息</div>
                                <Form class="clearfix padding-right-15 margin-top-5" ref="shipper" :model="shipperData" :label-width="160" :rules="shipperRules">
                                    <FormItem prop='shipperContactName' label="发货方:" class="relative">
                                        <span v-if="isquery">{{shipperData.shipperContactName}}</span>
                                        <Input v-else v-model="shipperData.shipperContactName"  placeholder='请选择' />
                                        <a @click="showShippers=true" class="absolute pointer" style="right:-0px;top:-32px;z-index:5;" v-if="!isquery">地址簿</a>
                                    </FormItem>
                                    <FormItem prop='shipperCode' label="发货方Code:" >
                                        <span v-if="isquery">{{shipperData.shipperCode?shipperData.shipperCode:shipperData.shipperWarehouseCode}}</span>
                                        <Input v-else v-model="shipperData.shipperCode" @on-blur="isDataCode(shipperData.shipperCode)"/>
                                    </FormItem>
                                    <FormItem prop="shipperCountrycode" label="国家:" >
                                        <span v-if="isquery">{{shipperData.shipperCountrycode}}</span>
                                        <Select v-else v-model="shipperData.shipperCountrycode" clearable>
                                            <Option v-for="(item,index) in getCountryList" :key="index" :value="item.value">{{item.label}}</Option>
                                        </Select>
                                    </FormItem>
                                    <FormItem prop="shipperState" label="州:" >
                                        <span v-if="isquery">{{shipperData.shipperState}}</span>
                                        <div v-else>
                                            <Select v-if="shipperData.shipperCountrycode == 'US'" v-model="shipperData.shipperState" clearable filterable >
                                                <Option v-for="val in getStateList" :key="val" :value="val">{{val}}</Option>
                                            </Select>
                                            <Input v-else v-model="shipperData.shipperState"></Input>
                                        </div>
                                    </FormItem>
                                    <FormItem prop="shipperCity" label="城市:" >
                                        <span v-if="isquery">{{shipperData.shipperCity}}</span>
                                        <Input v-else v-model="shipperData.shipperCity" />
                                    </FormItem>
                                    <FormItem prop="shipperZipcode" label="邮编:" >
                                        <span v-if="isquery">{{shipperData.shipperZipcode}}</span>
                                        <Input v-else v-model="shipperData.shipperZipcode" />
                                    </FormItem>
                                    <FormItem prop="shipperContactPhone" label="联系电话:" >
                                        <span v-if="isquery">{{shipperData.shipperContactPhone}}</span>
                                        <Input v-else v-model="shipperData.shipperContactPhone" />
                                    </FormItem>
                                    <FormItem prop="shipperAddressLine1" label="详细地址:">
                                        <span v-if="isquery">{{shipperData.shipperAddressLine1}}</span>
                                        <Input v-else v-model="shipperData.shipperAddressLine1" class="width-70per" />
                                        <Button class="margin-left-10" @click="saveReceData" v-if="!isquery">保存到地址薄</Button>
                                    </FormItem>
                                </Form>
                            </div>
                        </Col>
                        <Col span="12">
                            <div class="newbase-box" style="margin-left:8px;" :style="newheight">
                                <div class="newbase-title">收件信息</div>
                                <Form class="clearfix padding-right-15 margin-top-5" ref="receiver" :model="receiverData" :label-width="160" :rules="receiverRules" >
                                    <FormItem prop='receiverContactName' label="收货方名称:" class="relative">
                                        <span v-if="isquery">{{receiverData.receiverContactName}}</span>
                                        <Input v-else v-model="receiverData.receiverContactName"  placeholder='请选择' />
                                        <a @click="showReceivers=true" class="absolute pointer" style="right:0px;top:-32px;z-index:5" v-if="!isquery">地址簿</a>
                                    </FormItem>
                                    <FormItem prop="receiverCountrycode" label="国家:" >
                                        <span v-if="isquery">{{receiverData.receiverCountrycode}}</span>
                                        <Select v-else v-model="receiverData.receiverCountrycode" clearable>
                                            <Option v-for="(item,index) in getCountryList" :key="index" :value="item.value">{{item.label}}</Option>
                                        </Select>
                                    </FormItem>
                                    <FormItem prop="receiverState" label="州:" >
                                        <span v-if="isquery">{{receiverData.receiverState}}</span>
                                        <div v-else>
                                            <Select v-if="receiverData.receiverCountrycode == 'US'" v-model="receiverData.receiverState" clearable filterable >
                                                <Option v-for="val in getStateList" :key="val" :value="val">{{val}}</Option>
                                            </Select>
                                            <Input v-else v-model="receiverData.receiverState"></Input>
                                        </div>
                                    </FormItem>
                                    <FormItem prop="receiverCity" label="城市:" >
                                        <span v-if="isquery">{{receiverData.receiverCity}}</span>
                                        <Input v-else v-model="receiverData.receiverCity" />
                                    </FormItem>
                                    <FormItem prop="receiverZipcode" label="邮编:" >
                                        <span v-if="isquery">{{receiverData.receiverZipcode}}</span>
                                        <Input v-else v-model="receiverData.receiverZipcode" />
                                    </FormItem>
                                    <FormItem prop="receiverContactPhone" label="联系电话:" >
                                        <span v-if="isquery">{{receiverData.receiverContactPhone}}</span>
                                        <Input v-else v-model="receiverData.receiverContactPhone" />
                                    </FormItem>
                                    <FormItem prop="receiverAddressLine1" label="详细地址1:">
                                        <span v-if="isquery">{{receiverData.receiverAddressLine1}}</span>
                                        <Input v-else v-model="receiverData.receiverAddressLine1"/>
                                    </FormItem>
                                    <FormItem  label="详细地址2:">
                                        <span v-if="isquery">{{receiverData.receiverAddressLine2}}</span>
                                        <Input v-else v-model="receiverData.receiverAddressLine2"/>
                                    </FormItem>
                                    <!-- <FormItem  label="详细地址3:">
                                        <span v-if="isquery">{{receiverData.receiverAddressLine3}}</span>
                                        <Input v-else v-model="receiverData.receiverAddressLine3" class="width-70per" />
                                    </FormItem> -->
									<Button class="margin-left-10" @click="showSaveReceiver=true" v-if="!isquery">保存到地址薄</Button>
                                </Form>
                            </div>
                        </Col>
                    </Row>
                </Col>
                <Col span="8" style="padding-left:8px">
                    <div class="newbase-box" style="overflow:auto" :style="newlistheight">
                        <div class="newbase-title">跟踪信息</div>
                        <div class="padding-15">
                            <Timeline v-if="detailList.length>0">
                                <TimelineItem v-for="(item,index) in detailList" :key="index"><div>{{item.city||'--'}},{{item.state||'--'}},{{item.country||'--'}},{{item.status||'--'}},{{item.statusDetail||'--'}}</div>
                                <div>{{item.datetime||'--'}}</div></TimelineItem>
                            </Timeline>
                            <div v-else class="text-center">暂无数据...</div>
                        </div>
                    </div>
                    <div class="newbase-box margin-top-15">
                        <div class="newbase-title">参考选项</div>
                        <Form class="clearfix padding-right-15" ref="parcel" :model="parcelData" :label-width="160">
                            <FormItem label="Reference" >
                                <div>{{itemApiResponse.reference}}</div>
                            </FormItem>
                            <FormItem label="PO" >
                                <div>{{itemApiResponse.po}}</div>
                            </FormItem>
                            <FormItem label="Invoice" >
                                <div>{{itemApiResponse.invoice}}</div>
                            </FormItem>
                            <FormItem label="Department" >
                                <div>{{itemApiResponse.department}}</div>
                            </FormItem>

                        </Form>
                    </div>
                </Col>
            </Row>
            <Row v-if="pickUpData.pickupNumber">
                <Col span="24" >
                    <div class="newbase-box margin-top-15">
                        <div class="newbase-title">取件信息</div>
                        <div>
                            <Form class="clearfix padding-right-15 margin-top-5" :label-width="160"  ref='pickUpData' :model='pickUpData'>
                                <Row>
                                    <Col>
                                        <FormItem label="取件日期:" >
                                            <div>{{pickUpData.readyTime.split(' ')[0]}}</div>
                                        </FormItem>
                                    </Col>
                                    <Col>
                                        <FormItem label="取件时间:" >
                                            <div>{{pickUpData.readyTime.split(' ')[1]}}~{{ pickUpData.closeTime.split(' ')[1] }}</div>
                                        </FormItem>
                                    </Col>
                                    <Col>
                                        <FormItem label="取件码:" >
                                            <div>{{pickUpData.pickupNumber}}</div>
                                        </FormItem>
                                    </Col>
                                </Row>
                            </Form>
                        </div>
                    </div>
                </Col>
            </Row>
        </div>

        <compWrapper title="操作日志" theme="gray" class="margin-top-15" >
            <compLog :data="logDetail" :columns="logcolumn"/>
        </compWrapper>

		<Modal class="label-modal" v-model="showShippers" title="发货方地址" :width='800' @on-ok='confirmAddress(true)' @on-cancel='searchData={}'>
			<div class="width-50per margin-bottom-15 relative" @keyup.enter='getAddressList(true)'>
				<Input placeholder="输入发货方名称搜索" v-model="searchData.shipper"/>
				<Icon class="absolute pointer" :size="22" type="ios-search-strong" @click.native="getAddressList(true)" style="padding:5px 7px;right:0;top:0;background-color:#2d8cf0;color:#fff;" ></Icon>
			</div>

			<stable v-if="showShippers" :formData='{search:{EQ_active:1}}' ref="shipperTable" url='/api/jwt/spl/shipper/query' highlight-row @on-current-change='getCurrentRow' :columns='shipperTabel' />
			<!-- <div slot='footer'></div> -->
		</Modal>
		<Modal class="label-modal" v-model="showReceivers" title="收货方地址" :width='800' @on-ok='confirmAddress(false)' @on-cancel='searchData={}'>
			<div class="width-50per margin-bottom-15 relative" @keyup.enter='getAddressList(false)'>
				<Input placeholder="输入收货方名称搜索" v-model="searchData.receiver"/>
				<Icon class="absolute pointer" :size="22" type="ios-search-strong" @click.native="getAddressList(false)" style="padding:5px 7px;right:0;top:0;background-color:#2d8cf0;color:#fff;" ></Icon>
			</div>
			<stable v-if="showReceivers" ref="receiverTabel"  url='/api/jwt/spl/receiver/query' highlight-row @on-current-change='getCurrentRow' :columns='receiverTabel' />
		</Modal>

		<Modal  v-model="showSaveShipper" title="保存地址" @on-ok='updateShipper' :mask-closable='false'>
            <div class="text-center padding-10" style="font-size:16px;">
                是否将地址保存到地址簿
            </div>
		</Modal>
		<Modal v-model="showSaveReceiver" title="保存地址" @on-ok='updateReceiver' :mask-closable='false'>
            <div class="text-center padding-10" style="font-size:16px;">
                是否将地址保存到地址簿
            </div>
		</Modal>
		<Modal  v-model="isCalculate" title="服务测算" :width="700" :mask-closable='false' class="hidefooter">
			<calculate   ref="calculate"  :manual='false'/>
			<div slot='footer'></div>
		</Modal>

        <Modal
        class="hidefooter"
		v-model='operate.show'
		:mask-closable='false'
		v-bind="operate">
			<component :is="operate.component" @on-close="operate={}" v-bind="operate"/>
			<footer slot="footer" v-show="operate.footer"></footer>
		</Modal>
		<!-- 全局弹框 -->
		<compModal
			v-model="modalProps.show"
			v-bind="modalProps"
            @on-close="closemodalprops"
		>
            <component :is="modalProps.component" v-bind="modalProps" v-on="modalProps.on" ></component>
        </compModal>

		<Spin size="large" fix v-if="loading"></Spin>
    </div>
</template>

<script>
import {
	HttpSaveLabel,
	HttpShipperList,
	HttpSaveShipper,
	HttpSaveReceiver,
	HttpLabelList,
	HttpLabelDetail,
	HttpCancelWaybill,
	HttpPrintWaybill,
	HttpWaybill,
	HttpRemoveWaybill,
    HttpCarrierCancelPickUP
} from '@/service/api/views';
// import record from '@/components/recordlog';
import stable from './stable';
import calculate from './calculate';
import {mapGetters,mapState} from 'vuex'
import { FSAPI } from '@/utils/assist';
import compapiDetail from './apidetail.vue'
import compAppointPickUp from './appointpickup.vue'
export default {
	props:['actived','trackDetail'],
	components: {  stable, calculate, compapiDetail, compAppointPickUp },
	data() {
		return {
			loading: true,
            isquery: false,
            isShowShip:false,
			id: this.$route.params.id || this.actived,
            trackDetail:this.$route.query.trackDetail || this.trackDetail,
            detailList:[],
            operate: {
                id: null,
                title: "",
                show: false,
                component: null
            },
			shipperData: {
				shipperCountrycode: '',
				shipperState: '',
				shipperCity: '',
				shipperZipcode: '',
				shipperContactName: '',
				shipperContactPhone: '',
				shipperAddressLine1: '',
				shipperCode: '',
				shipperWarehouseCode:'',
			},
			receiverData: {
				receiverContactName: '',
				receiverCountrycode: '',
				receiverState: '',
				receiverCity: '',
				receiverZipcode: '',
				receiverContactName: '',
				receiverContactPhone: '',
                receiverAddressLine1: '',
                receiverAddressLine2: '',
                receiverAddressLine3: '',
			},
			parcelData: {
				parcelLengthUnit: 'inch',
				parcelWeightUnit: 'lbs',
				parcelLength: '',
				parcelWidth: '',
				parcelHeight: '',
				parcelWeight: '',
			},
			incrementData: {
				valuation: 0,
				parcelDeclareValue: '',
				trackingStatus: '',
				signfor: 0,
			},
			otherData: {
				carrier: '',
				serviceCode: '',
				parcelNo: '',
				labelPrintAmount: 0,
				status: 0,
				cancel: 0,
				trackingCode: '',
				rate: '',
				currency: '',
                systemSource:0,
                apiRequest:'',
                apiResponse:'',
                isInternational:0,
                organizationId:0,
				rateInfo:{},
                returnLabel: 0,
			},
            pickUpData: {

            },
			currentRow: {},
			shipperRules: {},
			receiverRules: {},
			carrierRule: null,
            itemApiResponse:{},

			showShippers: false,
			showReceivers: false,
			showSaveShipper: false,
			showSaveReceiver: false,
			isCalculate: false,
			searchData: {
				shipper: '',
				receiver: '',
			},
			shipperTabel: [
				{
					title: 'NO',
					type: 'index',
					width: 60,
				},
				{
					title: '发货方名称',
					key: 'contactName',
				},
				{
					title: '地址',
					key: 'countrycode',
					render(h, { row }) {
						let address = `${row.countrycode} ${row.state}  ${row.city}  ${row.addressLine1 || ''}`;
						return h('span', address);
					},
				},
			],
			receiverTabel: [
				{
					title: 'NO',
					type: 'index',
					width: 60,
				},
				{
					title: '收货方名称',
					key: 'contactName',
				},
				{
					title: '地址',
					key: 'countrycode',
					render(h, { row }) {
						let address = `${row.countrycode} ${row.state}  ${row.city}  ${row.addressLine1 || ''}`;
						return h('span', address);
					},
				},
			],

			requireRule: [
				{
					required: true,
					message: '该信息不能为空,请填写'
				},
			],
            logDetail:[],
			modalProps:{
                show:false
            },
            getLogActions:{
                "100": this.$ct('global.common.create', { defaultValue: "创建" }),
                "200": this.$ct('fbb.alloment.update	', { defaultValue: "更新" }),
                "310": "获取记录",
                "400": this.$ct('global.common.operate_cancel', { defaultValue: "取消" }),
                "500": "预约取件",
                "520": "取消预约取件"
            },
		};
	},
	created() {
		this.shipperRules = this.validate(this.shipperData);
		this.receiverRules = this.validate(this.receiverData);
        this.detailList = JSON.parse(this.trackDetail || null) || []
		this.carrierRule = [
			{
				validator: (rule, value, callback) => {
					if (this.otherData.serviceCode) {
						if (value) {
							callback();
						} else {
							callback(new Error('该信息不能为空,请填写'));
						}
					} else {
						callback();
					}
				},
			},
		];
		this.getLabelDetail();
	},
	computed:{
		...mapGetters('common',['getStateList']),
        ...mapGetters('dictionary', ['getCountryList','getSysAllList']),
		newheight(){
			return this.actived ? 'height:425px' : 'height:390px'
		},
		newlistheight(){
			return this.actived ? 'height:513px' : 'height:479px'
		},
        logcolumn(){
            return [
                {
                    title: this.$ct("global.common.operator"),
                    key: "createdName"
                },
                {
                    title: this.$ct("global.common.operate_time"),
                    key: "createdAt"
                },
                {
                    title: this.$ct("global.common.operate_remark", {
                        defaultValue: "备注"
                    }),
                    key: "opRemark",
                    render: (h, { row }) => {
                        const value = row.opAction || row.operateType || row.action;
                        return (
                            <div>
                                <div>
                                    {this.$ct("global.common.operate_type")}:
                                    {this.getLogActions[value] || value}
                                </div>
                                <div>
                                    {this.$ct("global.common.operate_note")}:
                                    {row.opRemark || row.remark || row.opResult}
                                </div>
                                <div>
                                    {this.$t("global.common.actions")}数据:
                                    {row.opData || '--'}
                                </div>
                            </div>
                        );
                    }
                }
            ]
        }
	},
	methods: {
        closemodalprops(){
            this.modalProps.show = false;
            this.$emit('on-openCloseable');
        },
        getOrgName(orgid){
            let oneorg = this.getSysAllList.filter(item=>{ return item.value === orgid }) [0] || {}
            return oneorg.label
        },
        getStatus(val){
            let type = ''
            switch (val) {
                case 'unknown': type = "初始化"; break;
                case 'pre_transit': type = "待发运"; break;
                case 'in_transit': type = "在途"; break;
                case 'out_for_delivery': type = "派送中"; break;
                case 'available_for_pickup': type = "派送中"; break;
                case 'delivered': type = "已妥投"; break;
                case 'return_to_sender': type = "已退回"; break;
                case 'cancelled': type = "已取消"; break;
                case 'failure': type = "异常"; break;
                case 'error': type = "异常"; break;
            }
            return type;
        },
        getServiceCode(value){
            let val = ''
            switch(value){
                case 'FEDXG':val = 'Ground';break;
                case 'FEDSP':val = 'Smart Post';break;
                case 'FEDHD':val = 'Home Delivery';break;
                case 'UPSG':val = 'UPSG';break;
            }
            return val
        },
        queryApi(){
            this.operate = {
                show: true,
                apiRequest: this.otherData.apiRequest,
                apiResponse:this.otherData.apiResponse,
                title: "查看API",
                component: "compapiDetail",
                width: '1000',
                footer: false
            }
        },
        appointPickUp(){
            const resoureData = {
                trackingCode: this.otherData.trackingCode,
                serviceCode: this.otherData.serviceCode,
                carrier: this.otherData.carrier,
                shipperCode: this.shipperData.shipperCode,
                remark: '',
                packageCount: 1,
                packageLocation: '',
                address:{
                    contactName: this.shipperData.shipperContactName,
                    country: this.shipperData.shipperCountrycode,
                    state: this.shipperData.shipperState,
                    city: this.shipperData.shipperCity,
                    zip: this.shipperData.shipperZipcode,
                    phone: this.shipperData.shipperContactPhone,
                    street1: this.shipperData.shipperAddressLine1,
                    street2: this.shipperData.shipperAddressLine2 || '',
                }
            }
            this.modalProps = {
                show: true,
                title: "预约取件",
                component: "compAppointPickUp",
                width: '460',
                showFooter: false,
                resoureData,
                activeId: this.id,
                on:{
                    'on-success': ()=>{
                        this.closemodalprops();
                        this.getLabelDetail()
                    },
                    'on-close': ()=>{
                        this.closemodalprops();
                    }
                },
            }
        },
        canceltPickUp(){
            this.modalProps = {
                show: true,
                title: "取消预约取件",
                alert: 'primary',
                showDesc: true,
                params: { pickupNumber: this.pickUpData.pickupNumber, },
                formdata:[
                    {
                        label: "备注",
                        tag: "Input",
                        key: "remark",
                        span: 24,
                    }
                ],
                ajaxRequest: HttpCarrierCancelPickUP,
                width: '460',
                callback:(res)=>{
                    this.$Message.success(res.message);
                    this.getLabelDetail();
                }
            }
        },
		queryRate(){
			this.operate = {
                show: true,
                apiRequest: this.otherData.rateInfo.apiRequest,
                apiResponse:this.otherData.rateInfo.apiResponse,
                title: "查看API",
                component: "compapiDetail",
                width: '1000',
                footer: false
            }
		},
        clearShip(){
            this.shipperData = {
				shipperCountrycode: '',
				shipperState: '',
				shipperCity: '',
				shipperZipcode: '',
				shipperContactName: '',
				shipperContactPhone: '',
				shipperAddressLine1: '',
				shipperCode: '',
				shipperWarehouseCode:'',
            }
            this.isShowShip = false;
        },
        isDataCode(value){
            if(value){
                HttpShipperList({
                    "search[EQ_code]":value
                }).then(res=>{
                    console.log(res)
                    if(res.data.totalElements>0){
                        this.$Message.error('code系统已存在，请从地址薄选择');
                        this.shipperData.shipperCode = ''
                        return;
                    }
                },err=>{
                    this.$Message.error(err.message);
                })
            }
        },
        saveReceData(){
            if(this.shipperData.shipperCode){
                HttpShipperList({
                    "search[EQ_code]":this.shipperData.shipperCode
                }).then(res=>{
                    console.log(res)
                    if(res.data.totalElements>0){
                        this.$Message.error('code系统已存在，请从地址薄选择');
                        this.shipperData.shipperCode = ''
                        return;
                    }else{
                        this.showSaveShipper=true;
                    }
                },err=>{
                    this.$Message.error(err.message);
                })

            }
        },
		handleSize(key, val) {
			val = val || 0
			val = key === 'parcelWeight' ? val.toFixed(2) : Math.ceil(val);
			// this.$set(this.parcelData, key, val);
            this.parcelData[key] = val
		},
		validate(fields, rule) {
			const rules = {};
			rule = rule || {
				required: true,
				message: '该信息不能为空,请填写',
			};
			Object.keys(fields).forEach(key => {
				rules[key] = rule;
			});
			return rules;
		},
		getCurrentRow(currentRow) {
			this.currentRow = currentRow;
		},
		getAddressList(isShipper) {
			if (isShipper) {
				this.$refs.shipperTable.updateList({
					search: { EQ_active: 1, CN_contactName: this.searchData.shipper || '' },
				});
			} else {
				this.$refs.receiverTabel.updateList({ search: { CN_contactName: this.searchData.receiver || '' } });
			}
		},
		confirmAddress(isShipper) {
			const currentRow = this.currentRow;
			if (isShipper) {
				this.shipperData = {
					id: currentRow['id'],
					shipperContactName: currentRow['contactName'],
					shipperCode: currentRow['code'],
					shipperCountrycode: currentRow['countrycode'],
					shipperState: currentRow['state'],
					shipperCity: currentRow['city'],
					shipperZipcode: currentRow['zipcode'],
					shipperContactPhone: currentRow['contactPhone'],
					shipperAddressLine1: currentRow['addressLine1'],
                };
                if(currentRow.id){
                    this.isShowShip = true;
                }
			} else {
				this.receiverData = {
					id: currentRow['id'],
					receiverContactName: currentRow['contactName'],
					receiverCountrycode: currentRow['countrycode'],
					receiverState: currentRow['state'],
					receiverCity: currentRow['city'],
					receiverZipcode: currentRow['zipcode'],
					receiverContactPhone: currentRow['contactPhone'],
					receiverAddressLine1: currentRow['addressLine1'],
					receiverAddressLine2: currentRow['addressLine2'],
					receiverAddressLine3: currentRow['addressLine3'],
				};
			}
			this.currentRow = {};
			this.showShippers = false;
			this.showReceivers = false;
		},
		goRoute(name) {
			this.$router.push({ name });
		},
		async validator() {
			let shipper = await this.$refs['shipper'].validate();
			let receiver = await this.$refs['receiver'].validate();
			let parce = await this.$refs['parcel'].validate();
			let other = await this.$refs['otherData'].validate();
			// let increment = await this.$refs['increment'].validate();
			// console.log(increment, parce, receiver, shipper, other);
			return shipper && receiver && parce && other;
		},

		async updateShipper() {
			let valid = await this.$refs['shipper'].validate();
			if (!valid) return;
			const data = this.shipperData;
			let formdata = {
				contactName: data['shipperContactName'],
				code: data['shipperCode'],
				countrycode: data['shipperCountrycode'],
				state: data['shipperState'],
				city: data['shipperCity'],
				zipcode: data['shipperZipcode'],
				contactPhone: data['shipperContactPhone'],
				addressLine1: data['shipperAddressLine1'],
			};
			if (data.id) {
				formdata.id = data.id;
			}
			const res = await HttpSaveShipper(formdata).catch(res => {
				this.$Message.error(res.message || 'error');
			});
			if (res) {
				this.$Message.success(res.message || 'error');
			}
		},
		async updateReceiver() {
			let valid = await this.$refs['receiver'].validate();
			if (!valid) return;
			const data = this.receiverData;
			let formdata = {
				contactName: data['receiverContactName'],
				countrycode: data['receiverCountrycode'],
				state: data['receiverState'],
				city: data['receiverCity'],
				zipcode: data['receiverZipcode'],
				contactPhone: data['receiverContactPhone'],
				addressLine1: data['receiverAddressLine1'],
				addressLine2: data['receiverAddressLine2'],
				addressLine3: data['receiverAddressLine3'],
			};
			if (data.id) {
				formdata.id = data.id;
			}
			const response = await HttpSaveReceiver(formdata).catch(error => {
				this.$Message.error(error.message || 'error');
			});
			if (response) {
				this.$Message.success(response.message || 'success');
			}
		},

		async getLabelDetail() {
			const response = await HttpLabelDetail({ id: this.id }).catch(error => {
				this.$Message.error(error.message || 'error');
				this.loading = false;
			});
			if (response) {
				const data = response.data || {};
                this.logDetail = response.data.log;
                this.pickUpData = data.pickup || {};
				Object.keys(this.shipperData).forEach(key => {
					this.shipperData[key] = data[key];
				});
				Object.keys(this.receiverData).forEach(key => {
					this.receiverData[key] = data[key];
				});
				Object.keys(this.parcelData).forEach(key => {
					this.parcelData[key] = data[key];
				});
				Object.keys(this.incrementData).forEach(key => {
					this.incrementData[key] = data[key];
				});
				this.incrementData.valuation = this.incrementData.valuation == 1 ? 1 : 0;
				Object.keys(this.otherData).forEach(key => {
					this.otherData[key] = data[key];
				});
                this.isquery = this.otherData.status >= 1 || this.otherData.cancel == 1;
                if(data.shipperCode){
                    this.isShowShip = true;
                }
                this.itemApiResponse = response.data;
				this.loading = false;
			}
		},
		async submit() {
			let valid = await this.validator();
			if (valid) {
				const formdata = {
					...this.shipperData,
					...this.receiverData,
					...this.parcelData,
					...this.incrementData,
					...this.otherData,
				};
				formdata.id = this.id;
				const response = await HttpSaveLabel(formdata).catch(res => {
					this.$Message.error(res.message || 'error');
				});
				if (response) {
					this.goRoute('label');
					this.$Message.success(response.message || 'success');

				}
			}
		},
		async removeWaybill() {
			if (this.otherData.status != 0) {
				this.$Message.warning('不能删除该运单');
				return;
			}
			const response = await HttpRemoveWaybill({ id: this.id }).catch(res => {
				this.$Message.error(res.message || 'error');
			});
			if (response) {
				this.goRoute('label');
				this.$Message.success(response.message || 'success');
			}
		},
		async cancelWaybill() {
			if (this.otherData.status == 0) {
				this.$Message.warning('不能取消该运单');
				return;
			}
			const response = await HttpCancelWaybill({ id: this.id }).catch(res => {
				this.$Message.error(res.message || 'error');
			});
			if (response) {
				this.$Message.success(response.message || 'success');
				this.goRoute('label');
			}
		},
		async printWaybill() {
			this.$Message.warning({
				content: '正在打印处理中，请稍后。',
				duration: 0
			})
            this.handleWebfs(process.env.VUE_APP_APIURL_SHIP + "/api/jwt/spl/shippinginfo/batchPrint", { ids: this.id }, {
                executor: 'request',
                print: true,
                fileType: "application/pdf"
            }).catch(err => {
                this.$Message.error({
                    content: err.message,
                    duration: 30,
                    closable: true
                });
            });
            this.$Message.destroy();
		},
		async printWayInvoce() {
			this.$Message.warning({
				content: '正在打印处理中，请稍后。',
				duration: 0
			})
            this.handleWebfs(process.env.VUE_APP_APIURL_SHIP + "/api/jwt/spl/shippinginfo/batchPrint", { ids: this.id,type:'invo' }, {
                executor: 'request',
                print: true,
                fileType: "application/pdf"
            }).catch(err => {
                this.$Message.error({
                    content: err.message,
                    duration: 30,
                    closable: true
                });
            });
            this.$Message.destroy();
		},
		async handleCalculate() {
			if (this.otherData.status > 0) {
				this.$Message.warning('已经获取该运单,不能重复获取，请直接打印');
				return;
			}

			let valid = await this.validator();

			if (valid) {
				const formdata = {
					...this.shipperData,
					...this.receiverData,
					...this.parcelData,
					...this.incrementData,
					...this.otherData,
				};
				formdata.id = this.id;
				this.isCalculate = true;
				this.$nextTick(() => {
					this.$refs.calculate.submitCalculate(formdata);
				});
			}
		},
	},
};
</script>

